<template>
  <div class="home">
    <!-- 顶部代码仓库地址 -->
    <div class="repository-link">
      代码仓库： <a href="https://gitee.com/luren98/course-website.git" target="_blank">https://gitee.com/luren98/course-website.git</a>
    </div>
    
    <!-- 数据加载状态显示 -->
    <div v-if="loading" class="loading-status">
      <el-progress type="circle" :percentage="50" status="warning" />
      <p>正在加载课程数据...</p>
    </div>
    
    <!-- 课程类别列表 -->
    <div class="course-categories" v-if="!loading">
      <h2>课程分类</h2>
      <div class="category-cards">
        <div v-for="category in categories" :key="category.id" class="category-card">
          <h3>{{ category.name }}</h3>
          <div class="courses-grid">
            <div 
              v-for="course in category.courses" 
              :key="course.id" 
              class="course-card" 
              @click="goToCourseDetail(course.id)"
            >
              <div class="course-image">
                <img 
                  :src="course.picPaths || getDefaultCourseImage(course.name)" 
                  :alt="course.name"
                  @error="handleImageError"
                />
                <div class="course-overlay"></div>
              </div>
              <div class="course-info">
                <h4 class="course-name">{{ course.name }}</h4>
                <p class="course-description">{{ course.intro || course.description || '暂无简介' }}</p>
                <div class="course-time">
                  <i class="el-icon-time"></i>
                  {{ formatCourseTime(course.startTime, course.endTime) }}
                </div>
              </div>
            </div>
            <div v-if="category.courses.length === 0" class="no-courses">
              <el-empty description="暂无课程" :image-size="80"></el-empty>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { api } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'Home',
  setup() {
    const router = useRouter()
    const categories = ref([])
    const loading = ref(false)
    
    // 获取课程类别列表
    const fetchCategories = async () => {
      loading.value = true
      
      try {
        console.log('开始获取课程类别...')
        const response = await api.items.getAll(5)
        console.log('课程类别API返回数据:', response)
        
        let allCategories = []
        
        // 处理特殊情况：如果响应是数组（即使是空数组）
        if (Array.isArray(response)) {
          console.log('API返回数组格式数据')
          allCategories = response
        } 
        // 处理标准格式的响应（对象格式）
        else if (typeof response === 'object') {
          // 检查是否有错误
          if (response.errno !== undefined && response.errno !== 0) {
            console.error('API返回错误:', response)
            ElMessage.error(response?.message || '获取课程类别失败')
            loading.value = false
            return
          }
          
          // 检查data字段
          if (response.data) {
            if (Array.isArray(response.data)) {
              // 使用response.data作为实际数据
              allCategories = response.data
            } else if (typeof response.data === 'object') {
              // 如果data是对象，可能是因为后端返回了单个对象而不是数组
              console.log('API返回单对象格式数据，转换为数组')
              allCategories = [response.data]
            }
          } else {
            // 如果没有data字段，尝试直接使用response对象的属性
            console.log('API返回无data字段对象，尝试解析')
            // 检查response是否包含类别相关字段
            if (Object.keys(response).length > 0) {
              // 可能是一个单类别对象
              allCategories = [response]
            } else {
              console.error('API返回空对象:', response)
              ElMessage.error('获取课程类别数据为空')
              loading.value = false
              return
            }
          }
        } else {
          console.error('API返回数据格式错误（非对象/数组）:', response)
          ElMessage.error('获取课程类别数据格式错误')
          loading.value = false
          return
        }
        
        // 标准化类别数据格式，确保包含必要的字段
        allCategories = allCategories.map(category => {
          // 处理不同命名的id字段
          const id = category.id || category._id || category.categoryId || `cat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
          // 处理不同命名的名称字段
          const name = category.name || category.title || category.categoryName || '未命名类别';
          
          return {
            id,
            name,
            ...category // 保留其他原始字段
          };
        });
        
        // 处理空数组情况
        if (allCategories.length === 0) {
          console.log('API返回空数组（暂无课程类别）')
          ElMessage.info('暂无课程类别，请先添加')
        } 
        // 处理有数据的情况
        else {
          console.log('API返回有效类别数据，共', allCategories.length, '条')
          console.log('标准化后的类别数据:', allCategories)
          
          // 筛选前4个类别
          const top4Categories = allCategories.slice(0, 4)
          console.log('筛选后的前4个类别:', top4Categories)
          
          // 为每个类别获取对应的课程
          for (const category of top4Categories) {
            await fetchCoursesByCategory(category)
          }
          
          allCategories = top4Categories
        }
        
        // 添加一个"未分类"类别，用于显示categoryid为null的课程
        const uncategorized = {
          id: -1, // 使用特殊ID标识未分类
          name: '未分类',
          courses: []
        }
        
        // 获取未分类的课程
        await fetchUncategorizedCourses(uncategorized)
        
        // 如果有未分类的课程，将未分类添加到类别列表
        if (uncategorized.courses.length > 0) {
          allCategories.push(uncategorized)
        }
        
        categories.value = allCategories
        console.log('最终课程类别数据:', categories.value)
        
      } catch (error) {
        console.error('获取课程类别失败:', error)
        // 增强错误信息，提供更多上下文
        if (error.message.includes('ERR_FAILED')) {
          ElMessage.error('网络连接失败，请检查网络设置或稍后再试')
        } else if (error.response && error.response.status === 404) {
          ElMessage.error('请求的资源不存在')
        } else {
          ElMessage.error('获取课程类别失败，请稍后重试')
        }
      } finally {
        loading.value = false
      }
    }
    
    // 标准化课程数据的工具函数
    const normalizeCourseData = (courseData) => {
      // 检查数据是否有效
      if (!Array.isArray(courseData)) {
        return []
      }
      
      // 标准化课程数据，确保包含必要的字段
      return courseData.map(course => {
        // 处理不同命名的id字段
        const id = course.id || course._id || `course_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        // 处理不同命名的课程名称字段 - 增强处理以适应更多可能的字段名
        const name = course.name || course.title || course.courseName || course.course_title || course.subject || '未命名课程';
        // 处理不同命名的开始时间字段
        const startTime = course.startTime || course.beginTime || course.date || course.course_time || '';
        // 处理结束时间字段
        const endTime = course.endTime || course.finishTime || '';
        // 处理图片路径
        const picPaths = course.picPaths || course.image || course.img || '';
        // 处理简介字段
        const intro = course.intro || course.description || course.body || '';
        
        // 调试日志，帮助识别后端返回的字段名
        if (!course.name && !course.title) {
          console.log('检测到无标准名称字段的课程数据:', course)
        }
        
        return {
          id,
          name,
          startTime,
          endTime,
          picPaths,
          intro,
          ...course // 保留其他原始字段
        };
      })
    }
    
    // 获取指定类别下的课程
    const fetchCoursesByCategory = async (category) => {
      try {
        console.log(`开始获取类别${category.name}(${category.id})的课程...`)
        const response = await api.items.getAll(6, { categoryId: category.id })
        console.log(`类别${category.name}的课程API返回数据:`, response)
        
        let courseData = []
        
        // 正确处理后端响应格式
        if (response?.errno === 0 && Array.isArray(response.data)) {
          courseData = response.data
        } else if (Array.isArray(response)) {
          courseData = response
        } 
        
        // 使用标准化函数处理课程数据
        category.courses = normalizeCourseData(courseData)
        
        console.log(`类别${category.name}的最终课程数据:`, category.courses)
      } catch (error) {
        console.error(`获取类别${category.name}的课程失败:`, error)
        category.courses = []
      }
    }
    
    // 获取未分类的课程（categoryid为null的课程）
    const fetchUncategorizedCourses = async (category) => {
      try {
        console.log('开始获取未分类的课程...')
        let allCourses = []
        const response = await api.items.getAll(6)
        
        // 正确处理后端响应格式
        if (response?.errno === 0 && Array.isArray(response.data)) {
          allCourses = response.data
        } else if (Array.isArray(response)) {
          allCourses = response
        }
        
        // 筛选出categoryid为null或0的课程
        let uncategorizedCourses = allCourses.filter(course => 
          course.categoryid === null || course.categoryid === 0 || course.categoryId === null || course.categoryId === 0
        )
        
        // 使用标准化函数处理未分类课程数据
        category.courses = normalizeCourseData(uncategorizedCourses)
        
        console.log('未分类课程数据:', category.courses)
      } catch (error) {
        console.error('获取未分类课程失败:', error)
        category.courses = []
      }
    }
    
    // 跳转到课程详情页
    const goToCourseDetail = (courseId) => {
      router.push(`/course/detail/${courseId}`)
    }
    
    // 格式化课程时间
    const formatCourseTime = (startTime, endTime) => {
      if (!startTime && !endTime) return '时间待定';
      
      const formatDate = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
      };
      
      const start = formatDate(startTime);
      const end = formatDate(endTime);
      
      if (start && end) {
        return `${start}~${end}`;
      } else if (start) {
        return `从${start}开始`;
      } else {
        return `到${end}结束`;
      }
    };
    
    // 获取默认课程图片
    const getDefaultCourseImage = (courseName) => {
      // 根据课程名称生成不同的默认图片
      const colors = ['#42b983', '#409eff', '#e6a23c', '#f56c6c', '#67c23a', '#909399'];
      const colorIndex = courseName.length % colors.length;
      return `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="300" height="200" viewBox="0 0 300 200"><rect width="300" height="200" fill="${colors[colorIndex]}"/><text x="150" y="100" font-family="Arial" font-size="18" fill="white" text-anchor="middle">${courseName}</text></svg>`;
    };
    
    // 处理图片加载错误
    const handleImageError = (event) => {
      const courseName = event.target.alt;
      event.target.src = getDefaultCourseImage(courseName);
    };
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchCategories()
    })
    
    return {
      categories,
      goToCourseDetail,
      loading,
      formatCourseTime,
      getDefaultCourseImage,
      handleImageError
    }
  }
}
</script>

<style scoped>
.home {
  padding: 2rem;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 代码仓库地址样式 */
.repository-link {
  text-align: right;
  margin-bottom: 2rem;
  font-size: 1rem;
  color: #666;
  background: white;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.repository-link a {
  color: #42b983;
  text-decoration: none;
  font-weight: 500;
}

.repository-link a:hover {
  text-decoration: underline;
}

/* 加载状态样式 */
.loading-status {
  text-align: center;
  padding: 4rem;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.loading-status p {
  margin-top: 1rem;
  color: #909399;
  font-size: 1.1rem;
}

/* 课程类别样式 */
.course-categories h2 {
  font-size: 2rem;
  color: #303133;
  margin-bottom: 2rem;
  text-align: center;
  font-weight: 600;
  position: relative;
  padding-bottom: 1rem;
}

.course-categories h2::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 4px;
  background: linear-gradient(90deg, #42b983, #409eff);
  border-radius: 2px;
}

.category-cards {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.category-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  padding: 1.5rem;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.category-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.category-card h3 {
  font-size: 1.5rem;
  color: #303133;
  margin-bottom: 1.5rem;
  padding-bottom: 0.8rem;
  border-bottom: 2px solid #e6f7ff;
  font-weight: 600;
}

/* 课程网格布局 */
.courses-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.5rem;
}

/* 课程卡片样式 */
.course-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.course-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.course-image {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.course-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.course-card:hover .course-image img {
  transform: scale(1.05);
}

.course-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, transparent 60%, rgba(0, 0, 0, 0.3));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.course-card:hover .course-overlay {
  opacity: 1;
}

.course-info {
  padding: 1.2rem;
}

.course-name {
  font-size: 1.1rem;
  font-weight: 600;
  color: #303133;
  margin-bottom: 0.5rem;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 3em;
}

.course-description {
  font-size: 0.9rem;
  color: #606266;
  line-height: 1.5;
  margin-bottom: 0.8rem;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 2.8em;
}

.course-time {
  display: flex;
  align-items: center;
  font-size: 0.85rem;
  color: #909399;
  padding-top: 0.5rem;
  border-top: 1px solid #f0f0f0;
}

.course-time i {
  margin-right: 0.4rem;
  font-size: 0.9rem;
}

.no-courses {
  grid-column: 1 / -1;
  text-align: center;
  padding: 2rem;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .courses-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 900px) {
  .courses-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .home {
    padding: 1rem;
  }
  
  .repository-link {
    text-align: center;
    margin-bottom: 1.5rem;
    font-size: 0.9rem;
    padding: 0.8rem;
  }
  
  .course-categories h2 {
    font-size: 1.6rem;
    margin-bottom: 1.5rem;
  }
  
  .category-card {
    padding: 1.2rem;
  }
  
  .category-card h3 {
    font-size: 1.3rem;
  }
  
  .courses-grid {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .course-image {
    height: 140px;
  }
  
  .course-info {
    padding: 1rem;
  }
  
  .course-name {
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .course-categories h2 {
    font-size: 1.4rem;
  }
  
  .category-card h3 {
    font-size: 1.2rem;
  }
  
  .course-name {
    font-size: 0.95rem;
  }
  
  .course-description {
    font-size: 0.85rem;
  }
}
</style>